package com.ysp.summary.util;

import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ExcelUtil {

    /**
     *
     * @param fileName
     * @param response
     * @param excelWriter
     */
    public static void writerExcelFile(String fileName, HttpServletResponse response, ExcelWriter excelWriter) {
        ServletOutputStream outputStream = null;
        if (StringUtils.isBlank(fileName)){
            new Exception("导出Excel文件名称不能为空！");
        }
        if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")){
            fileName = fileName+".xls";
        }
        try {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            outputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO-8859-1"));
            excelWriter.flush(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            response.setContentType("text/javascript; charset=utf-8");
            try {
                response.getWriter().write("系统异常，请稍后再试");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                excelWriter.close();
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
